package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.core.utils.JsonUtils;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.ProductSummary;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.dto.DeviceDto;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.huawei.HuaweiIotUtil;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.qpid.proton.engine.Collector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;

import static com.zzyl.common.constant.CacheConstants.IOT_ALL_PRODUCT_LIST;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private HuaweiIotUtil huaweiIotUtil;
    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 互联网平台同步产品列表
     *
     * @return
     */
    @Override
    public void syncProductList() {
        List<ProductSummary> productList = huaweiIotUtil.queryProductList();
        List<ProductVo> productVos = BeanUtil.copyToList(productList, ProductVo.class);
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, productVos);

    }


    /**
     * 1.2 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        List<ProductVo> o = (List<ProductVo>) redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST);

        return o;
    }


    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        if (ObjectUtil.isNull(deviceDto.getPhysicalLocationType())) {
            deviceDto.setPhysicalLocationType(3);
        }

        //1.校验设备名称和标识码
        this.validateDeviceBeefore(deviceDto);


        //2.调用华为云，注册设备
        String s = IdUtil.simpleUUID();
        deviceDto.setSecret(s);//生成密钥
        String deviceId = this.huaweiIotUtil.addDevice(deviceDto);

        //3.保存信息到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(s);


        try {
            boolean save = this.save(device);
            if (!save) {
                this.huaweiIotUtil.removeDevice(deviceId);
                throw new BaseException("注册设备失败");
            }
        } catch (Exception e) {
            this.huaweiIotUtil.removeDevice(deviceId);
            throw new BaseException("注册设备失败");
        }


    }

    private void validateDeviceBeefore(DeviceDto deviceDto) {
        //1校验设备名称和标识码
        Long count = this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BeanException("设备名称已存在");
        }
        //2校验标识码
        count = this.lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BeanException("设备标识码已存在");
        }

        //3校验同一位置绑定对不对
        count = this.lambdaQuery()
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType()).count();
        if (count > 0) {
            throw new BeanException("该位置已经绑定了同类型的产品，请勿重复！");
        }
    }


    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceById(String iotId) {
        //1.查询设备
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //判断是不是空
        if (ObjectUtil.isEmpty(device)){
            return null;
        }
        //2.通过华为云工具查询设备详细数据
        ShowDeviceResponse showDeviceResponse = huaweiIotUtil.queryDeviceDetail(device.getIotId());
        //复制
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //通过华为云工具加入设置设备状态
        deviceDetailVo.setDeviceStatus(showDeviceResponse.getStatus());
        //通过华为云工具查看时间
        String activeTime = showDeviceResponse.getActiveTime();
         if (ObjectUtil.isNotEmpty(activeTime)){
             //转换时间，时区
             LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
             parse=parse.plusHours(8);
             deviceDetailVo.setActiveTime(parse);
         }

        String  createTime = showDeviceResponse.getCreateTime();
        if (ObjectUtil.isNotEmpty(createTime)){
            //转换时间，时区
            LocalDateTime parse = LocalDateTimeUtil.parse(createTime, "yyyyMMdd'T'HHmmss'Z'");
            parse=parse.plusHours(8);
            deviceDetailVo.setCreateTime(parse);
        }

        return deviceDetailVo;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public Object getInfo(String iotId) {
        List<DeviceShadowData> deviceShadowData = huaweiIotUtil.queryDeviceShadowData(iotId);
       if(ObjectUtil.isEmpty(deviceShadowData)){
           return Collections.emptyList();
       }


        JSONObject entries = JSONUtil.parseObj(deviceShadowData.get(0).getReported().getProperties());
        LocalDateTime parse = LocalDateTimeUtil.parse(deviceShadowData.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        parse.plusHours(8);

        ArrayList<Map<String, Object>> mapList = new ArrayList<>();
        entries.forEach((k, v) -> {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("functionId", k);
            stringObjectHashMap.put("value", v);
            stringObjectHashMap.put("eventTime", parse);
            mapList.add(stringObjectHashMap);
        });
         return mapList;
    }


    /**
     * 修改
     *
     * @param device
     * @return
     */
    @Override
    public void addid(Device device) {
        //修改iot
        huaweiIotUtil.updateDeviceInfo(device.getIotId(), device.getDeviceName());
        //查原来的，修改
        Device one = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, device.getNodeId()));
        BeanUtil.copyProperties(device, one);
        this.updateById(one);
    }

    /**
     * 删除
     *
     * @param iotId
     */
    @Override
    public void removeId(String iotId) {
        huaweiIotUtil.removeDevice(iotId);
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
    }
}
